package com.suoluo.zenadmin.common.file;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.suoluo.zenadmin.common.Application;
import com.suoluo.zenadmin.common.config.SystemConfigHolder;


/**
 * 
 * 文件操作工具
 * @author xiongxu
 *
 */
public final class FileUtils {

	private FileUtils(){
		
	}
	
	public static void saveFile(String filePath,byte[] data)
	{
		File file = new File(filePath);
		if (file.exists())
		{
			throw new FileException(filePath + " already exists");
		}
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			fos.write(data);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			throw new FileException("fail to save " + filePath,e);
		}
		finally{
			closeOutputStream(fos);
		}
	}
	
	public static String saveFile(String filePath,MultipartFile mfile){
		try {
			saveFile(filePath, mfile.getInputStream());
		} catch (IOException e) {
			throw new FileException("fail to save " + filePath, e);
		}
		return filePath;
	}
	
	public static void saveFile(String filePath, InputStream is)
	{
		File file = new File(filePath);
		if (file.exists())
		{
			throw new FileException(filePath + " already exists");
		}
		writeFile(file, is);
	}
	
	public static  void writeFile(File file,InputStream is){
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			byte [] data = new byte [512];
			int len = 0;
			while ((len = is.read(data)) > 0)
			{
				fos.write(data, 0, len);
			}
		} catch (IOException e) {
			throw new FileException("fail to save " + file.getAbsolutePath(),e);
		}
		finally{
			closeOutputStream(fos);
		}
	}
	
	/**
	 * 替换图片
	 * @param filePath 被替换的文件路径
	 * @param mfile 替换的文件
	 */
	public static void replaceFile(String oldFilePath,String newFileName,MultipartFile mfile){
		File oldFile = new File(oldFilePath);
		try {
			//验证该文件的目录是否
			File parentDir = oldFile.getParentFile();
			if (!parentDir.exists()){
				parentDir.mkdirs();
			}
//			mkdirIfNotExsits(parentDir);
			if (oldFile.exists()){
				oldFile.delete();
			}
			writeFile(new File(parentDir, newFileName), mfile.getInputStream());
		} catch (IOException e) {
			throw new FileException("fail to replace file + " + newFileName,e);
		}
	}
	
	/**
	 * 关闭输出流
	 * @param os 输出流
	 */
	public static void closeOutputStream(OutputStream os){
		if (os != null){
			try {
				os.close();
			} catch (IOException e) {
				throw new FileException("fail to close output stream.",e);
			}
		}
	}
	
	/**
	 * 关闭输出流
	 * @param os 输出流
	 */
	public static void closeIutputStream(InputStream is){
		if (is != null){
			try {
				is.close();
			} catch (IOException e) {
				throw new FileException("fail to close output stream.",e);
			}
		}
	}
	
	public static byte[] readFile(String fileName) throws IOException{
		String relactiveFilePath = SystemConfigHolder.getUploadImageRoot() + fileName;
		String filePath = Application.getInstance().getPath(relactiveFilePath);
//		InputStream is = Timeline.class.getClassLoader().getResourceAsStream(filename);
		BufferedInputStream bufferedInputStream = null;
		try{
			InputStream is = new FileInputStream(filePath);
			bufferedInputStream = new BufferedInputStream(is);
			int len = bufferedInputStream.available();
			byte[] bytes = new byte[len];
			int r = bufferedInputStream.read(bytes);
			if (len != r) {
				bytes = null;
				throw new IOException("读取文件不正确");
			}
			return bytes;
		}finally{
			closeIutputStream(bufferedInputStream);
		}
	}
	
	/**
	 * 解析文件名称的后缀<br>
	 * eg:'aaa.jpg',返回'.jpg'
	 * @param fileName 文件名称
	 * @return String 返回文件名称的后缀
	 */
	public static String parseFileNameSuffix(String fileName)
	{
		if (!StringUtils.hasLength(fileName)){
			throw new IllegalArgumentException("file name is null");
		}
		int index = fileName.lastIndexOf(".");
		if (index == -1){
			throw new FileException("invalid fileName,no suffix ,[fileName=" + fileName +"]");
		}
		return fileName.substring(index);
	}
	
	private static class FileException extends RuntimeException{

		/**
		 * 
		 */
		private static final long serialVersionUID = 7455069989204300190L;
		
		
		public FileException(String msg){
			super(msg);
		}
		
		public FileException(String msg,Throwable e){
			super(msg,e);
		}
	}
	
//	public static void main(String [] args){
//		System.out.println(parseFileNameSuffix("aa.aaa.jpg"));
//	}
}
